using System;
using System.Collections.Generic;

namespace Common.Core.Objects
{
	public abstract class ObjectFinderBase<SourceType,ObjectType> : IObjectFinder
	{
		public event EventHandler<ObjectFindingEventArgs<SourceType,ObjectType>> Finding = delegate { };

		protected virtual IEnumerable<ObjectType> List
		{
			get { return null; }
		}

		protected virtual ObjectType FindItem( SourceType source )
		{
			return default(ObjectType);
		}

		public ObjectType Find( SourceType source )
		{
			var args = new ObjectFindingEventArgs<SourceType, ObjectType>( List, source ) { Result = FindItem( source ) };
			Finding( this, args );
			return args.Result;
		}

		protected virtual SourceType ResolveKey( object source )
		{
			var result = (SourceType)source;
			return result;
		}

		protected virtual ObjectType DefaultValue
		{
			get{ return default( ObjectType ); }
		}

		object IObjectFinder.Find( object key )
		{
			var resolveKey = ResolveKey( key );
			var result = !Equals( resolveKey, default( SourceType ) ) ? Find( resolveKey ) : DefaultValue;
			return result;
		}
	}
}